package controllers

import (
	"github.com/gin-gonic/gin"
	"meituan/apps/shop/models"
	db2 "meituan/db"
	"meituan/utils/response"
)

func QueryCategory(ctx *gin.Context) {
	db, _ := db2.NewDB()
	defer db.Close()
	result := make([]models.Category, 10)
	query := db.Preload("Categories").Where("parent_id = 0").Model(new(models.Category))
	query.Find(&result)
	ctx.JSON(200, gin.H{
		"code": 200,
		"data": result,
		"msg":  "获取成功",
	})
}

func DeleteCategory(ctx *gin.Context) {
	db, _ := db2.NewDB()
	defer db.Close()
	db.Model(new(models.Category)).
		Where(" id = ?", ctx.Param("id")).Delete(new(models.Category))
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}

func UpdateCategory(ctx *gin.Context) {
	form := new(models.Category)
	if e := ctx.ShouldBindJSON(form); e != nil {
		db, _ := db2.NewDB()
		defer db.Close()
		db.Model(form).
			Where(" id = ?", ctx.Param("id")).
			Omit("id").
			Update(form)
		ctx.JSON(200, gin.H{
			"code": 200,
			"data": form,
			"msg":  "修改成功",
		})
	} else {
		response.SendError(ctx, e, 400)
	}
}

func CreateCategory(ctx *gin.Context) {
	form := new(models.Category)
	if e := ctx.ShouldBindJSON(form); e != nil {
		db, _ := db2.NewDB()
		defer db.Close()
		db.Model(form).Create(form)
		ctx.JSON(200, gin.H{
			"code": 200,
			"data": form,
			"msg":  "新建成功",
		})
	} else {
		response.SendError(ctx, e, 400)
	}

}
